package com.gogowan.agroenterprise.supply;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.base.BaseActivity;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.model.CollectionDescResultInfo;
import com.gogowan.agroenterprise.model.CollectionSDResultInfo;
import com.gogowan.agroenterprise.model.CommodityRequst;
import com.gogowan.agroenterprise.model.EnterpriseDetailInfo;
import com.gogowan.agroenterprise.model.IntegrateQuestInfo;
import com.gogowan.agroenterprise.model.Message;
import com.gogowan.agroenterprise.model.ResultInfo;
import com.gogowan.agroenterprise.model.SupplyDemandDescInfo;
import com.gogowan.agroenterprise.supply.utils.SupplyAndDemandUtils;
import com.gogowan.agroenterprise.utils.Utils;

public class CollectionDetailActivity extends BaseActivity{
	
	private TextView title,introduction,content,enterpriseDescription;
	private Button check,discollect;
	private LinearLayout refresh;
	//private SharedPreferences preferences;
	//private long enterpriseId;
	private ProgressDialog progressDialog;
	private CollectionDescResultInfo materialResultInfo;
	private int type;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.supply_collection_detail);
        
        title = (TextView)findViewById(R.id.collection_detail_title);
		introduction = (TextView)findViewById(R.id.collection_detail_introduction);
		//date = (TextView)findViewById(R.id.collection_detail_date);
		content = (TextView)findViewById(R.id.collection_detail_content);
		enterpriseDescription  = (TextView)findViewById(R.id.collection_detail_enterprise_description);
		check = (Button)findViewById(R.id.collection_detail_btn_check);
		discollect = (Button)findViewById(R.id.collection_detail_btn_discollect);
		refresh = (LinearLayout)findViewById(R.id.collection_detail_btn_refresh);
		
		//preferences = getSharedPreferences("LoginINfo", MODE_PRIVATE);
		//enterpriseId = preferences.getLong("enterpriseid", 0);
		
        Intent intent = getIntent();
        String detail = intent.getStringExtra("CollectionDetail");
        type = intent.getIntExtra("Type", 0);
        
        if (type == 1) {
        	check.setEnabled(false);
		}
        
        if (detail == null || detail.equals("")) {
        	showFinishDialog("提示","初始化数据失败！",false);
		} else {
			materialResultInfo = (CollectionDescResultInfo)Utils.fromJSON(detail, CollectionDescResultInfo.class);
			if (materialResultInfo == null) {
				showFinishDialog("提示","异常数据！",false);
			} else {
				String titleString =  materialResultInfo.getTitle();
				String introdutctionString = materialResultInfo.getIntroduction();
				//String dateString = materialResultInfo.getTimeDown();
				String contentString = materialResultInfo.getDescription();
				
				if (titleString == null || titleString.equals("")) {
					showFinishDialog("提示", "异常数据(标题null)！", false);
				} else {
					title.setText(SupplyAndDemandUtils.ToDBC(titleString));
				}

				if (introdutctionString == null || introdutctionString.equals("")) {
					showFinishDialog("提示", "异常数据(简介null)！", false);
				} else {
					introduction.setText(SupplyAndDemandUtils.ToDBC(introdutctionString));
				}

				/*if (dateString == null || dateString.equals("")) {
					showFinishDialog("提示", "异常数据(产品过期时间null)！", false);
				} else {
					date.setText(dateString);
				}*/
				
				if (contentString == null || contentString.equals("")) {
					showFinishDialog("提示", "异常数据(详细介绍null)！", false);
				} else {
					content.setText(SupplyAndDemandUtils.ToDBC(contentString));
				}
				
				EnterpriseDetailInfo enterpriseInfo = materialResultInfo.getEnterpriseInfo();
				if (enterpriseInfo != null) {
					String enterpriseString = enterpriseInfo.getEnterpriseDescription();
					if (enterpriseString == null || enterpriseString.equals("")) {
						enterpriseDescription.setText("未获取到企业信息");
					} else {
						enterpriseDescription.setText(SupplyAndDemandUtils.ToDBC(enterpriseString));
					}
				} else {
					enterpriseDescription.setText("未获取到企业信息");
				}
			}
		}
        
        check.setOnClickListener(checkCallback);
		discollect.setOnClickListener(discollectCallback);
		refresh.setOnClickListener(refreshCallback);
	}
	
	
	/**
	 * 刷新点击事件
	 */
	public Button.OnClickListener refreshCallback = new Button.OnClickListener(){

		@Override
		public void onClick(View v) {
			IntegrateQuestInfo integrateQuestInfo = new IntegrateQuestInfo();
			integrateQuestInfo.setSdID(materialResultInfo.getSdID());
			progressDialog = ProgressDialog.show(CollectionDetailActivity.this,
					getString(R.string.alert_title),
					getString(R.string.alert_message), true, false);
			
			RefreshAsyn refreshAsyn = new RefreshAsyn();
			refreshAsyn.execute(integrateQuestInfo);
		}
		
	};
	/**
	 * 查看详细信息点击事件
	 */
	public Button.OnClickListener checkCallback = new Button.OnClickListener(){

		@Override
		public void onClick(View v) {
			CommodityRequst commodityRequst = new CommodityRequst();
			commodityRequst.setCommodityID(materialResultInfo.getMaterialID());
			
			progressDialog = ProgressDialog.show(CollectionDetailActivity.this,
					getString(R.string.alert_title),
					getString(R.string.alert_message), true, false);
			
			GetCommodityInfoAsyn getCommodityInfoAsyn = new GetCommodityInfoAsyn(CollectionDetailActivity.this, progressDialog);
			getCommodityInfoAsyn.execute(commodityRequst);
		}
		
	};
	
	/**
	 * 取消收藏按钮点击事件
	 */
	public Button.OnClickListener discollectCallback = new Button.OnClickListener(){

		@Override
		public void onClick(View v) {
			
			AlertDialog alert = new AlertDialog.Builder(CollectionDetailActivity.this)
			.setTitle("警告")
			.setMessage("确实要取消此条记录的收藏吗?").setCancelable(false)
					.setNegativeButton("否", new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							// do nothing
						}
					})
					.setPositiveButton("是", new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							CollectionSDResultInfo collectionSDResultInfo = new CollectionSDResultInfo();
							collectionSDResultInfo.setCollectionID(materialResultInfo.getCollectionID());
							
							progressDialog = ProgressDialog.show(CollectionDetailActivity.this,
									getString(R.string.alert_title),
									getString(R.string.alert_message), true, false);
							
							DeleteCollectionAsyn deleteCollectionAsyn = new DeleteCollectionAsyn();
							deleteCollectionAsyn.execute(collectionSDResultInfo);
						}
					}).create();
			alert.show();
			
		}
		
	};
	
	/**
	 * 错误退出此页finish
	 * @param s 对话框标题
	 * @param string 对话框内容
	 */
	private void showFinishDialog(String s,String string,final Boolean isRefresh){
    	new AlertDialog.Builder(CollectionDetailActivity.this).setTitle(s)
		.setMessage(string).setPositiveButton("确定", new DialogInterface.OnClickListener() {
	
			@Override
			public void onClick(DialogInterface dialog, int which) {
				if (isRefresh) {
					
				} else {
					CollectionDetailActivity.this.finish();
				}
			}
		}).create().show();
    }
	
	/**
	 * 取消收藏异步
	 * @author Maniac
	 *	2012.12.20
	 */
	private class DeleteCollectionAsyn extends MyAsyncTask{

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(CollectionDetailActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
			} else {
				
				Message message = (Message) Utils.fromJSON((String) res, Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					Toast.makeText(CollectionDetailActivity.this, getString(R.string.analyse_error), Toast.LENGTH_LONG).show();
				} else {
					ResultInfo resultInfo = (ResultInfo)Utils.fromJSON(string, ResultInfo.class);
					int result = resultInfo.getResult();
					if (result == 8510) {
						setResult(RESULT_OK);
						Toast.makeText(CollectionDetailActivity.this, resultInfo.getResultinfo(), Toast.LENGTH_LONG).show();
						CollectionDetailActivity.this.finish();
						Utils.randomAnim(CollectionDetailActivity.this);
					} else {
						Toast.makeText(CollectionDetailActivity.this, resultInfo.getResultinfo(), Toast.LENGTH_LONG).show();
					}
				}
			}
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			CollectionSDResultInfo request = (CollectionSDResultInfo)params[0];
			String json = Utils.toJSON(request);
			Message message = new Message(8500, true, json);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}
	}
	
	/**
	 * 刷新最新信息
	 * @author MANIAC
	 * 2012.12.27
	 */
	private class RefreshAsyn extends MyAsyncTask{

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(CollectionDetailActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
			} else {
				
				Message message = (Message) Utils.fromJSON((String) res, Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					Toast.makeText(CollectionDetailActivity.this, getString(R.string.analyse_error), Toast.LENGTH_LONG).show();
				} else {
					SupplyDemandDescInfo supplyDemandDescInfo = (SupplyDemandDescInfo)Utils.fromJSON(string, SupplyDemandDescInfo.class);
					
					int result = supplyDemandDescInfo.getResult();
					
					if (result == 6210 || result == 7210) {
						
						String titleString =  supplyDemandDescInfo.getTitle();
						String introdutctionString = supplyDemandDescInfo.getIntroduction();
						//String dateString = supplyDemandDescInfo.getTimeDown();
						String contentString = supplyDemandDescInfo.getDescription();
						
						if (titleString == null || titleString.equals("")) {
							showFinishDialog("提示", "异常数据(标题null)！", true);
						} else {
							title.setText(titleString);
						}

						if (introdutctionString == null || introdutctionString.equals("")) {
							showFinishDialog("提示", "异常数据(简介null)！", true);
						} else {
							introduction.setText(introdutctionString);
						}

						/*if (dateString == null || dateString.equals("")) {
							showFinishDialog("提示", "异常数据(产品过期时间null)！", true);
						} else {
							date.setText(dateString);
						}*/
						
						if (contentString == null || contentString.equals("")) {
							showFinishDialog("提示", "异常数据(详细介绍null)！", true);
						} else {
							content.setText(contentString);
						}
						
						EnterpriseDetailInfo enterpriseInfo = supplyDemandDescInfo.getEnterpriseInfo();
						if (enterpriseInfo != null) {
							String enterpriseString = enterpriseInfo.getEnterpriseDescription();
							if (enterpriseString == null || enterpriseString.equals("")) {
								enterpriseDescription.setText("未获取到企业信息");
							} else {
								enterpriseDescription.setText(enterpriseString);
							}
						} else {
							enterpriseDescription.setText("未获取到企业信息");
						}
					
					} else if (result == -6220 || result == -7220) {
						//如果这条信息已不存在则删除
						AlertDialog alert = new AlertDialog.Builder(CollectionDetailActivity.this)
						.setTitle("警告")
						.setMessage(supplyDemandDescInfo.getResultinfo() + ",要删除这条收藏记录吗?").setCancelable(false)
								.setNegativeButton("否", new AlertDialog.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										// do nothing
									}
								})
								.setPositiveButton("是", new AlertDialog.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										CollectionSDResultInfo collectionSDResultInfo = new CollectionSDResultInfo();
										collectionSDResultInfo.setCollectionID(materialResultInfo.getCollectionID());
										
										progressDialog = ProgressDialog.show(CollectionDetailActivity.this,
												getString(R.string.alert_title),
												getString(R.string.alert_message), true, false);
										
										DeleteCollectionAsyn deleteCollectionAsyn = new DeleteCollectionAsyn();
										deleteCollectionAsyn.execute(collectionSDResultInfo);
									}
								}).create();
						alert.show();
					}
				}
			}
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			IntegrateQuestInfo request = (IntegrateQuestInfo)params[0];
			String json = Utils.toJSON(request);
			
			Message message = null;
			if (type == 0) {
				message = new Message(6200, true, json);
			} else if (type == 1) {
				message = new Message(7200, true, json);
			}
			
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}
		
		
	}
}
